<?php
/**
 * Created by PhpStorm.
 * User: zhangligang
 * Date: 17/5/8
 * Time: 下午7:54
 */

namespace App\Http\Controllers;

use App\Http\Models\Article;
use App\Http\Models\Language;
use App\Http\Presenter\ArticlePresenter;
use App\Http\Repository\ArticleRepository;
use App\Http\Service\ArticleService;
use Illuminate\Http\Request as HttpRequest;

class ArticleController extends BaseController
{

    public function __construct(ArticlePresenter $presenter, ArticleRepository $repository, ArticleService $service)
    {

        $this->view = ['activeFirst' => 'article', 'activeSecond' => 'index'];

        parent::__construct($presenter, $repository, $service);

    }

    public function index()
    {

        $articleList = Article::all(['id', 'poster', 'title', 'status']);

        return view('article.index', array_merge(['articleList' => $articleList], $this->view));
    }

    public function create()
    {

        $article = new Article();

        $languageList = Language::get(['id', 'title']);

        $this->view['activeSecond'] = 'create';

        return view('article.edit', array_merge(['article' => $article, 'languageList' => $languageList], $this->view));
    }

    public function update($id)
    {

        $article = Article::query()->find($id);

        $languageList = Language::get(['id', 'title']);

        return view('article.edit', array_merge(['article' => $article, 'languageList' => $languageList], $this->view));
    }

    public function save(HttpRequest $request)
    {

        $articleArray = $request->all();

        $article = Article::query()->firstOrCreate($articleArray);

        return redirect('article.html');
    }

    public function delete(HttpRequest $request)
    {

        $id = (int)$request->get('id', 1);

        $code = 200;

        $message = '删除成功';

        if (Article::query()->where('id', '=', $id)->delete() === false) {

            $code = 404;

            $message = '删除失败,请重试';
        }

        return $this->send($code, $message);
    }


}